import React, { lazy, Suspense, useEffect, useState } from 'react'
import { 
  Space, Table, Tag, Button, message, Modal, Spin, Input, Card, Typography, 
  Tooltip, Descriptions, DatePicker 
} from 'antd'
import type { TableProps, SpinProps } from 'antd';
import type { RangePickerProps } from 'antd';
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, FileTextOutlined, CheckCircleOutlined, EyeOutlined } from '@ant-design/icons'
import http from '../api/http'
import type { IUsers } from '../types/users'
import type { Iganyuf } from '~/types/ganyuf';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');

type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection'];

const { Column } = Table;
const { Title, Text } = Typography;
const AddUserForm = lazy(() => import('./add'));

const Users: React.FC = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [searchValue, setSearchValue] = useState('');
  // 新增：时间范围查询状态
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs | null, dayjs.Dayjs | null]>([null, null]);
  
  // 查看报告弹窗相关状态
  const [isReportModalOpen, setIsReportModalOpen] = useState(false);
  const [currentReportData, setCurrentReportData] = useState<Iganyuf | null>(null);
  const [reportLoading, setReportLoading] = useState(false);

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const handleAddSuccess = () => {
    setIsModalOpen(false);
    fetchUsers(1, 3,'2025-10-01','2025-11-12','');
  };

  const jia = () => {
    setIsModalOpen(true);
  };

  // 表格选择相关
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  
  const rowSelection: TableRowSelection<Iganyuf> = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: '选择奇数行',
        onSelect: (changeableRowKeys) => {
          const newSelectedRowKeys = changeableRowKeys.filter((_, index) => index % 2 === 0);
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: 'even',
        text: '选择偶数行',
        onSelect: (changeableRowKeys) => {
          const newSelectedRowKeys = changeableRowKeys.filter((_, index) => index % 2 !== 0);
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };

  // 加载状态和数据管理
  const [loading, setLoading] = useState<boolean | SpinProps>({
    size: 'large'
  });
  const [count, setCount] = useState(0);
  const [data, setData] = useState<Array<Iganyuf>>([]);

  // 获取用户数据（新增时间范围参数）
  const fetchUsers = async (
    page: number, 
    size: number, 
   
    startDate?: string,
    endDate?: string,
     search?: string
  ) => {
    setLoading({ size: 'large' });
    try {
      const response = await http.getList<Iganyuf>('Ganyuf', { 
        page, 
        size,        
        startTime:startDate||'',  // 传递开始时间
        endTime:endDate||'',
        name:search || ''       // 传递结束时间
      });

      const response1= await http.getList<Iganyuf>('Ganyuf', { 
        page:1, 
        size:3,
        startTime:'2025-10-01',  // 传递开始时间
        endTime:'2025-11-12',
        name:''  // 传递结束时间
      });
    
      console.log('原始响应:', response1);
     
      console.log('zz',response1.data)
      setData(response.data);
      setCount(response.count);
    } catch (error) {
      message.error('获取数据失败，请重试');
      console.error('数据获取失败:', error);
    } finally {
      setTimeout(() => {
        setLoading(false);
      }, 200);
    }
  };

  // 获取报告详情
  const getReportDetail = async (record: Iganyuf) => {
    setReportLoading(true);
    try {
      const response = await http.get<Array<Iganyuf>>('Ganyuf/chay');
      const targetReport = response.data.find(n => n.id === record.id);
      setCurrentReportData(targetReport || null);
      setIsReportModalOpen(true);
    } catch (error) {
      message.error('获取报告详情失败');
      console.error('报告获取失败:', error);
    } finally {
      setReportLoading(false);
    }
  };

  // 查看报告按钮点击事件
  const viewReport = (record: Iganyuf) => {
    getReportDetail(record);
  };

  // 关闭报告弹窗
  const handleReportCancel = () => {
    setIsReportModalOpen(false);
    setCurrentReportData(null);
  };

  // 初始化数据
  useEffect(() => {
    fetchUsers(1, 3,'2025-10-01','2025-11-12','');
  }, []);

  // 搜索功能（整合时间范围）
const handleSearch = () => {
  // 用更稳妥的方式获取时间，避免可选链导致的空值
  const start = dateRange[0] ? dateRange[0].format('YYYY-MM-DD') : '';
  const end = dateRange[1] ? dateRange[1].format('YYYY-MM-DD') : '';
  console.log('搜索时的时间范围：', start, end); // 额外加日志确认
  fetchUsers(1, 3, start, end, searchValue);
};

  // 重置搜索条件
  const handleResetSearch = () => {
    setSearchValue('');
    setDateRange([null, null]);
    fetchUsers(1, 3,'2025-01-01','2025-12-12','');
  };

  // 格式化时间
  const formatDate = (dateStr?: string | number | null) => {
    if (!dateStr || dateStr === '' || isNaN(Number(dateStr)) && typeof dateStr !== 'string') {
      return '-';
    }

    const date = dayjs(dateStr);
    if (!date.isValid()) {
      return '无效时间';
    }

    return date.format('YYYY-MM-DD HH:mm:ss');
  };

  // 刷新数据（携带当前筛选条件）
  const shua = () => {
    console.log("刷新数据");
    const startDate = dateRange[0]?.format('YYYY-MM-DD') || '';
    const endDate = dateRange[1]?.format('YYYY-MM-DD') || '';
    fetchUsers(1, 3, startDate, endDate ,searchValue);
  };

  // 渲染报告状态
  const renderReportStatus = (status: number) => {
    switch (status) {
      case 0:
        return <Tag icon={<FileTextOutlined />} color="default">未生成报告</Tag>;
      case 1:
        return <Tag icon={<CheckCircleOutlined />} color="success">已生成报告</Tag>;
      default:
        return <Tag color="gray">未知状态</Tag>;
    }
  };

  return (
    <Card 
      title={<Title level={4} style={{ margin: 0 }}>健康测评列表</Title>}
      style={{ margin: 20 }}
      bodyStyle={{ padding: '20px 16px' }}
    >
      {/* 操作栏 */}
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={jia}
          >
            添加测评
          </Button>
          
          <Button 
            danger 
            onClick={shua}
            style={{ 
              backgroundColor: '#faad14', 
              borderColor: '#faad14', 
              color: '#fff' 
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.backgroundColor = '#f59a00';
              e.currentTarget.style.borderColor = '#f59a00';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.backgroundColor = '#faad14';
              e.currentTarget.style.borderColor = '#faad14';
            }}
          >
            刷新数据
          </Button>
          
        </Space>
        
        {/* 搜索框（添加时间范围选择器） */}
        <Space.Compact style={{ width: 600, gap: 16 }}>
          <DatePicker.RangePicker
            placeholder={['开始日期', '结束日期']}
            value={dateRange}
            onChange={(dates) => setDateRange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null])}
            format="YYYY-MM-DD"
            style={{ width: 280 }}
          />
          <Input
            placeholder="搜索姓名或档案号"
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
            onPressEnter={handleSearch}
            style={{ width: 200 }}
          />
          <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
            搜索
          </Button>
          <Button onClick={handleResetSearch}>
            重置
          </Button>
        </Space.Compact>
      </div>

      {/* 表格 */}
      <Table<Iganyuf>
        loading={loading}
        dataSource={data}
        rowKey="id"
        pagination={{
          total: count,
          defaultCurrent: 1,
          defaultPageSize: 3,
          showTotal: (total) => `共 ${total} 条记录`,
          showSizeChanger: true,
          showQuickJumper: true,
          pageSizeOptions: ['3', '10', '20', '50', '100'],
          position: ['bottomCenter'],
          onChange: (page, size) => {
            const startDate = dateRange[0]?.format('YYYY-MM-DD') || '';
            const endDate = dateRange[1]?.format('YYYY-MM-DD') || '';
            fetchUsers(page, size, searchValue, startDate, endDate);
          }
        }}
        bordered
        scroll={{ x: 'max-content' }}
        style={{ background: '#fff' }}
      >
        <Column 
          title="档案号" 
          dataIndex="fileNumber" 
          key="fileNumber"
          width={120}
          sorter={(a, b) => (a.fileNumber || '').localeCompare(b.fileNumber || '')}
        />
        <Column 
          title="姓名" 
          dataIndex="name" 
          key="name"
          width={100}
          sorter={(a, b) => (a.name || '').localeCompare(b.name || '')}
        />
        <Column 
          title="性别" 
          dataIndex="sex" 
          key="sex"
          width={80}
          filters={[
            { text: '男', value: '男' },
            { text: '女', value: '女' },
          ]}
          onFilter={(value, record) => record.sex === value}
        />
        <Column 
          title="测评日期" 
          dataIndex="fdata" 
          key="fdata"
          width={180}
          render={(text) => formatDate(text)}
        />
        <Column 
          title="操作人" 
          dataIndex="uname" 
          key="uname"
          width={120}
        />
        <Column 
          title="报告状态" 
          dataIndex="zt" 
          key="zt"
          width={140}
          render={(status) => renderReportStatus(status || 0)}
          filters={[
            { text: '未生成报告', value: 0 },
            { text: '已生成报告', value: 1 },
          ]}
          onFilter={(value, record) => record.zt === value}
        />
        <Column
          title="操作"
          key="action"
          width={160}
          render={(_: any, record: Iganyuf) => (
            <Space size="small">
               <Tooltip 
                title={record.zt === 0 ? "报告未生成，无法查看" : "查看健康报告"}
                placement="top"
              >
                <Button 
                  type="primary" 
                  icon={<EyeOutlined />} 
                  size="small"
                  onClick={() => viewReport(record)}
                  disabled={record.zt === 0}
                  style={{ 
                    opacity: record.zt === 0 ? 0.6 : 1,
                    cursor: record.zt === 0 ? 'not-allowed' : 'pointer'
                  }}
                >
                  查看报告
                </Button>
              </Tooltip>
            </Space>
          )}
        />
      </Table>

      {/* 添加用户弹窗 */}
      <Modal
        title="添加健康测评"
        open={isModalOpen}
        onCancel={handleCancel}
        maskClosable={false}
        width={1000}
        footer={null}
      >
        <Suspense fallback={<Spin size="large" style={{ display: 'block', margin: '20px auto' }} />}>
          <AddUserForm 
            onSuccess={handleAddSuccess} 
            onCancel={handleCancel} 
            onGenerateReport={() => {
              setIsModalOpen(false);
              message.success('报告已生成');
              const startDate = dateRange[0]?.format('YYYY-MM-DD') || '';
              const endDate = dateRange[1]?.format('YYYY-MM-DD') || '';
              fetchUsers(1, 3, searchValue, startDate, endDate);
            }}
          />
        </Suspense>
      </Modal>

      {/* 查看报告弹窗 */}
      <Modal
        title={<Title level={5} style={{ margin: 0 }}>健康报告详情</Title>}
        open={isReportModalOpen}
        onCancel={handleReportCancel}
        maskClosable={false}
        width={800}
        footer={[
          <Button key="close" onClick={handleReportCancel}>
            关闭
          </Button>
        ]}
      >
        {reportLoading ? (
          <div style={{ textAlign: 'center', padding: '50px 0' }}>
            <Spin size="large" />
            <p style={{ marginTop: 16 }}>加载报告中...</p>
          </div>
        ) : currentReportData ? (
          <Card bodyStyle={{ padding: '20px' }}>
            <Descriptions
              bordered
              column={2}
              size="small"
              title={<Text strong>基础信息</Text>}
            >
              <Descriptions.Item label="档案号">{currentReportData?.fileNumber || '-'}</Descriptions.Item>
              <Descriptions.Item label="姓名">{currentReportData.name || '-'}</Descriptions.Item>
              <Descriptions.Item label="性别">{currentReportData.sex || '-'}</Descriptions.Item>
              <Descriptions.Item label="年龄">{currentReportData.age || '-'}</Descriptions.Item>
              <Descriptions.Item label="测评日期">{formatDate(currentReportData.fdata)}</Descriptions.Item>
              <Descriptions.Item label="操作人">{currentReportData.uname || '-'}</Descriptions.Item>
            </Descriptions>

            <div style={{ marginTop: 24, padding: '16px', backgroundColor: '#f5f5f5', borderRadius: 6 }}>
              <Text strong style={{ fontSize: 15 }}>风险评估报告：</Text>
              <div style={{ marginTop: 8, lineHeight: 1.8, fontSize: 14 }}>
                {currentReportData.pinj || '暂无评估结论'}
              </div>
            </div>

            <div style={{ marginTop: 20 }}>
              <Text strong>详细信息：</Text>
              <div style={{ marginTop: 8, lineHeight: 1.6 }}>
                <p>• 本人疾病：{currentReportData.benb || '无'}</p>
                <p>• 亲属疾病：{currentReportData.qinb || '无'}</p>
                <p>• 饮食评估：{currentReportData.yins || '未评估'}</p>
                <p>• 体力评估：{currentReportData.tili || '未评估'}</p>
                <p>• 吸烟状态：{currentReportData.xiyan === 0 ? '不吸烟' : '吸烟'}</p>
              </div>
            </div>
          </Card>
        ) : (
          <div style={{ textAlign: 'center', padding: '50px 0', color: '#999' }}>
            <p>暂无报告数据</p>
          </div>
        )}
      </Modal>
    </Card>
  );
};

export default Users;